package com.my.config;

import cn.hutool.core.bean.BeanUtil;
import com.my.domain.entity.User;
import com.my.service.UserService;
import com.my.utils.AccountProfile;
import com.my.utils.JwtToken;
import com.my.utils.JwtUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/*
realm实现AuthorizingRealm主有两个方法
一个认证一个授权。
授权
 */

@Component
public class UserRealm extends AuthorizingRealm {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //在你第一次登录的时候进行授权，只执行了这一次，
        System.out.print("===================================================="+"执行了授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        AccountProfile accountProfile = (AccountProfile)principals.getPrimaryPrincipal();
        System.out.println("=============================userrealm的44行accountprofile==========================="+accountProfile);
        String  role = accountProfile.getType();
        System.out.println(role+"--------------------------------------------");
            info.addRole(role);
            if(role.equals("0")){
                System.out.println("授权user*");
                info.addStringPermission("user:*");
            }
            else if( role.equals("1")){
                System.out.println("授权user*与repair*");
                info.addStringPermission("user:*");
                info.addStringPermission("repair:*");
            }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        System.out.print("===================================================="+"执行了认证");

        JwtToken jwtToken = (JwtToken) token;
        //得到subject用户id
        String userId = jwtUtils.getClaimByToken((String) jwtToken.getPrincipal()).getSubject();
        //获得user
        User user = userService.getById(Long.valueOf(userId));
        if (user == null) {
            throw new UnknownAccountException("账户不存在");
        }

        if (user.getDelFlag() == 0) {
            throw new LockedAccountException("账户已被锁定");
        }

        AccountProfile profile = new AccountProfile();
        //把user中对应的字段copy到profile中进行封装
        BeanUtil.copyProperties(user, profile);

        //jwtToken.getCredentials() --> jwt
        return new SimpleAuthenticationInfo(profile, jwtToken.getCredentials(), getName());
    }
}
